const pool = require("../config/dbPool");   //引入mysql模块

function getConnection(){
	return new Promise((resolve, reject)=>{
		pool.getConnection((err, connection) => {
			if (err) {
				throw new Error('数据库链接异常');
			}
			resolve(connection);
		});
	})
}

async function beginTransaction(connection){
	connection = connection ? connection: await getConnection();
	return new Promise((resolve, reject)=>{
		connection.beginTransaction(function (err) {
			if (err) {
				throw new Error('数据库开启事务异常');
			}
			resolve(true);
		});
	})
}
function releaseConnection(connection){
	if(pool._freeConnections.indexOf(connection) == -1){
		connection.release();
	}
}

async function rollback(connection){
	connection = connection ? connection: await getConnection();
	return new Promise((resolve, reject)=>{
		connection.rollback(function (err) {
			if (err) {
				throw new Error('数据库回滚事务异常');
			}
			releaseConnection(connection);
			resolve(true);
		});
	})
}

async function commit(connection){
	return new Promise((resolve, reject)=>{
		connection.commit(function (err) {
			if (err) {
				throw new Error('数据库提交事务异常');
			}
			releaseConnection(connection);
			resolve(true);
		});
	})
}

function queryByPage(p1, p2, p3){
	if(arguments.length != 3){
		return;
	}
	if(p2.pageSize < 0 && p2.pageNum < 0){
		return;
	}
	p2.pageNum = parseInt(p2.pageNum);
	p2.pageSize = parseInt(p2.pageSize);
// 拼接分页参数
	const offset = (p2.pageNum - 1) * p2.pageSize;
	const limit = p2.pageSize;
	let sql = `
		select * from (
		   ${p1} 
		) t limit ?,?
	`;
	const arr = p2.param ? p2.param: [];
	query(sql, [offset, limit, ...arr], p3);
}

function queryCount(p1, p2, p3){
	let sql = `
		SELECT COUNT(*) count FROM (${p1})t
	`;

	if(arguments.length == 2){
		query1(sql, p2);
	}
	if(arguments.length == 3){
		query2(sql, p2, p3);
	}
}

function query(p1, p2, p3){
	if(arguments.length == 2){
		query1(p1, p2);
	}
	if(arguments.length == 3){
		query2(p1, p2, p3);
	}
}

function query1(sql, callback) {
	pool.getConnection(function(err, connection) {
			connection.query(sql, function(err, rows) {
				console.log('执行sql', sql)
				callback(err, rows);
			});
		releaseConnection(connection);
	});
}

function query2(sql, params, callback) {
	pool.getConnection(function(err, connection) {
		connection.query(sql, params, function(err, rows) {
			console.log('执行sql', sql)
			callback(err, rows);
		});
		releaseConnection(connection);
	});
}


exports.query = query;
exports.queryByPage = queryByPage;
exports.queryCount = queryCount;
